/**
 * Created by admin on 2016/11/7.
 */
var co = require('co');
var redis = require("redis");
var assert = require('./../assert');

//获取指定商品
exports.getKDProduct = function (req, res) {
    var kdProductId = req.params.id;
    if (assert.check_parms([kdProductId])){
        res.json(assert.con2json(101, 'id不能为空'));
        return;
    }
    var isShort = req.query.isShort;
    var unvisited = req.query.unvisited;
    var userId = req.query.userId;
    var hasUser = (userId != '' && typeof userId != 'undefined');
    isShort = (isShort != '' && typeof isShort != 'undefined');
    // 异步转同步方法
    co(function* () {
        // 查询微店商品
        try {
            var kdProduct = yield new Promise(function (resolve, reject) {
                var query = new Parse.Query('OPStoreGoods');
                query.include('product', 'store');
                query.select('salePrice', 'isSale', 'product', 'store');
                if (isShort){
                    query.select('product');
                }
                query.get(kdProductId).then(function (result) {
                    resolve(result);
                }, function (error) {
                    reject(new Error(error.message));
                });
            });
        }catch (error){
            res.json(assert.con2json(102, error.message));
            return;
        }
        var shopId = kdProduct.get('store').id;
        //如果是未被记录的访问,则记录访问历史
        var redis_client = assert.getRedis();
        if(unvisited){
            // 插入总的浏览记录
            redis_client.get(shopId, function (err, reply) {
                var pv = 0;
                if (reply != "NaN" && reply != null){
                    pv = parseInt(reply);
                }
                pv += 1;
                redis_client.set(shopId, pv, redis_client.print);
            });
            if (hasUser){
                // 获取用户如果有userId，就把这个用户的浏览记录保存起来
                redis_client.hset(shopId.split("").reverse().join(""), new Date().toISOString(), userId);
            }
            if(redis_client){
                redis_client.quit();
            }
        }
        if (isShort){
            var response_temp = assert.obj2dic(kdProduct,['salePrice']);
            response_temp['product'] = assert.obj2dic(kdProduct.get('product'), ['title']);
            response_temp['product']['images'] = kdProduct.get('product').get('images')[0];
            response_temp['storeName'] = kdProduct.get('store').get('name');
            response_temp['storeId'] = kdProduct.get('store').id;
            res.json(assert.con2json(200, 'get success',response_temp));
        }else {
            var kd_temp = assert.obj2dic(kdProduct, ['isSale', 'salePrice']);
            kd_temp['product'] = assert.obj2dic(kdProduct.get('product'), ['images', 'title', 'country', 'price', 'info', 'detailImages', 'saleCount']);
            var return_store = {};
            var kdStore = kdProduct.get('store');
            return_store.name = typeof kdStore.get('name') == 'undefined'? '店名暂无' : kdStore.get('name');
            return_store.objectId = typeof kdStore.id == 'undefined'? '' : kdStore.id;
            // 对头像的url进行过滤，对开头是http的进行处理
            var avatar_url = kdStore.get('avatar');
            return_store.avatar = assert.checkAvatar(avatar_url);
            kd_temp['store'] = return_store;
            res.json(assert.con2json(200, 'get success', kd_temp));
        }
    });
};
//获取指定kd微店
exports.getKDShop = function (req, res) {
    var shopId = req.params.id;
    var userId = req.query.userId;
    var unvisited = req.query.unvisited;
    if (shopId == '' || typeof shopId == 'undefined'){
        res.json(assert.con2json(101, 'id不能为空'));
        return;
    }
    var redis_client = assert.getRedis();
    if(unvisited){
        // 插入总的浏览记录
        redis_client.get(shopId, function (err, reply) {
            var pv = 0;
            if (reply != "NaN" && reply != null){
                pv = parseInt(reply);
            }
            pv += 1;
            redis_client.set(shopId, pv, redis_client.print);
        });
    }
    // 获取用户如果有userId，就把这个用户的浏览记录保存起来
    if (userId != '' && typeof userId != 'undefined'){
        redis_client.hset(shopId.split("").reverse().join(""), new Date().toISOString(), userId);
    }
    if(redis_client){
        redis_client.quit();
    }
    // 异步转同步方法
    co(function* () {
        // 查询微店商品
        try {
            // 先从redis中查询
            // client = redis.createClient();
            var kdShop = yield new Promise(function (resolve, reject) {
                var query = new Parse.Query('OPStore');
                query.include('user');
                query.get(shopId).then(function (result) {
                    resolve(result);
                }, function (error) {
                    reject(new Error(error.message));
                });
            });
        }catch (error){
            res.json(assert.con2json(102, error.message));
            return;
        }
        // 查询店铺内的商品
        try {
            var shopProducts = yield new Promise(function (resolve, reject) {
                var query = new Parse.Query('OPStoreGoods');
                query.include('product', 'product.type', 'category');
                query.equalTo('store', kdShop);
                query.descending('createdAt');
                query.find().then(function (result) {
                    resolve(result);
                }, function (error) {
                    reject(new Error(error.message));
                });
            });
        }catch (error){
            res.json(assert.con2json(103, error.message));
            return;
        }
        // 格式化返回的内容
        var response_content = {};
        response_content['shopInfo'] = assert.obj2dic(kdShop,['ownerName', 'naviStyle', 'listStyle']);
        response_content['shopInfo'].name = typeof kdShop.get('name') ==  'undefined' || kdShop.get('name') == ''? '暂无店名': kdShop.get('name');
        response_content['shopInfo'].desc = typeof kdShop.get('desc') ==  'undefined' || kdShop.get('desc') == ''? '暂无简介': kdShop.get('desc');
        response_content['shopInfo'].ownerName = typeof kdShop.get('ownerName') ==  'undefined' || kdShop.get('ownerName') == ''? '暂无': kdShop.get('ownerName');
        response_content['shopInfo'].avatar = assert.checkAvatar(kdShop.get('avatar'));
        response_content['shopInfo'].backIdCard = typeof kdShop.get('cover') == 'undefined' ? assert.DEFAULT_BACKGROUND:kdShop.get('cover');
        response_content['shopInfo']['wechat'] = typeof kdShop.get('wechat') == 'undefined' || kdShop.get('wechat') == ''? '暂无' : kdShop.get('wechat');
        response_content['shopInfo']['template'] = kdShop.get('templet');
        response_content['shopInfo']['count'] = shopProducts.length;
        var category_list = [];
        var category_products = {};
        if (shopProducts.length > 3){
            category_products.mainPage = shopProducts.slice(0, 3);
        }else {
            category_products.mainPage = shopProducts;
        }
        shopProducts.forEach(function (item) {
            var product_temp = assert.obj2dic(item.get('product'),['title', 'images']);
            var category = item.get('category');
            // 前期容错，如果category在初始化的时候是undefined，直接把category标记为other
            var cate_name = '其他';
            if (typeof category == 'undefined'){
                category = {'name': cate_name};
                product_temp['category'] = category;
            }else {
                product_temp['category'] = assert.obj2dic(category, ['name']);
                cate_name = category.get('name');
            }
            var kdProduct_temp = assert.obj2dic(item, ['salePrice']);
            kdProduct_temp['product'] = product_temp;
            // 给array添加属性，判断在array中是否包含某个值
            Array.prototype.contains = function(element){
                return this.indexOf(element) > -1;
            };
            if (!category_list.contains(cate_name)){
                category_list.push(cate_name);
                category_products[cate_name] = [];
            }
            category_products[cate_name].push(kdProduct_temp);
        });
        response_content['shopProducts'] = category_products;
        res.json(assert.con2json(200, 'get success', response_content));
    });
};

exports.createKdOrder = function (req, res) {
    var userId = req.body.userId;
    var addressId = req.body.addressId;
    var cost = 0;
    var remark = req.body.remark;
    if (typeof remark == 'undefined'){
        remark = '';
    }
    var store = undefined;
    try {
        var products = req.body.products;
        if (typeof products == 'string'){
            products = JSON.parse(products);
        }else {
            console.log('not string')
        }
    }catch (error){
        res.json(assert.con2json(101, '商品信息获取错误'));
        return;
    }
    if (assert.check_parms([userId, addressId])){
        res.json(assert.con2json(102, '用户ID和地址ID为空'));
        return;
    }

    co(function* () {
        // 获取用户的地址
        try {
            var userAddress = yield new Promise(function (resolve, reject) {
                var query = new Parse.Query('OPAddress');
                query.get(addressId).then(function (address) {
                    resolve(address);
                }, function (error) {
                    reject(error)
                });
            });
        }catch (error){
            res.json(assert.con2json(103, error.message));
            return;
        }
        // 生成对应的orderProduct对象
        try {
            var orderProducts = yield new Promise(function (resolve, reject) {
                var OrderProduct = Parse.Object.extend('OPOrderProduct');
                var productList = [];
                for (var i=0; i<products.length; i++){
                    (function (i) {
                        var query = new Parse.Query('OPStoreGoods');
                        query.include('product', 'store');
                        productList[i] = query.get(products[i]['product']);
                    })(i);
                }
                Promise.all(productList).then(function (pList) {
                    var orderProducts = [];
                    if (pList.length > 0){
                        store = pList[0].get('store');
                    }
                    for(var j=0;j<pList.length;j++){
                        var StoreGood = Parse.Object.extend('OPStoreGood');
                        var storeGood = new StoreGood();
                        storeGood.id = products[j].product;
                        var count = parseInt(products[j]['count']);
                        var price = pList[j].get('salePrice');
                        // 成本计算
                        cost += pList[j].get('product').get('cost') * count;
                        var orderProduct = new OrderProduct();
                        orderProduct.set('product', pList[j].get('product'));
                        orderProduct.set('message', '');
                        orderProduct.set('price', price);
                        orderProduct.set('count', count);
                        orderProduct.set('storeGood', storeGood);
                        orderProducts[j] = orderProduct.save();
                    }
                    Promise.all(orderProducts).then(function (orderProductSaved) {
                        resolve(orderProductSaved);
                    },function (error) {
                        reject(error)
                    });
                });
            });
        }catch (error){
            res.json(assert.con2json(104, error.message));
            return;
        }
        // 计算总价
        var totalPrice = 0;
        orderProducts.forEach(function (item) {
            totalPrice += item.get('price') * item.get('count');
        });
        // 计算支付价
        var payPrice = totalPrice;
        // 生成user
        var User = Parse.Object.extend('User');
        var user = new User();
        user.id = userId;
        // 生成order
        var Order = Parse.Object.extend('OPOrder');
        var order = new Order();
        order.set('user', user);
        order.set('mobile', userAddress.get('tel'));
        order.set('status', 0);
        order.set('cost', cost);
        order.set('store', store);
        order.set('remark', remark);
        order.set('privilegePrice', 0);
        order.set('address', userAddress.get('province')+userAddress.get('city')+userAddress.get('district')+userAddress.get('address'));
        order.set('username', userAddress.get('name'));
        order.set('payPrice', payPrice);
        order.set('totalPrice', totalPrice);
        order.set('expressPrice', 0);
        order.set('orderProducts', orderProducts);
        order.save().then(function (order) {
            res.json(assert.con2json(200, '生成订单成功', {'objectId': order.id, 'payPrice': order.get('payPrice')}));
            deleteShoppingItem(products, user);
        }, function (error) {
            res.json(assert.con2json(400, '生成订单失败'))
        });
    });
};

// kd微店搜索
exports.kdSearch = function (req, res) {
    var keyWord = req.query.keyWord;
    var page = req.query.page;
    var storeId = req.query.storeId;
    if (assert.check_parms([storeId, keyWord])){
        res.json(assert.con2json(101, 'storeId或keyWord为空'));
        return;
    }
    try {
        page = parseInt(page);
    }catch (error){
        page = 1
    }
    // 设定控制值
    var limit = 10;
    var skip = (page-1) * limit;
    keyWord = decodeURI(keyWord);
    var Store = Parse.Object.extend('OPStore');
    var store = new Store();
    store.id = storeId;
    var goodsQuery = new Parse.Query('OPStoreGoods');
    goodsQuery.equalTo('store', store);
    goodsQuery.include('product');
    var productQuery = new Parse.Query('OPProduct');
    productQuery.contains('title', keyWord);
    productQuery.skip(skip);
    productQuery.limit(limit);
    goodsQuery.matchesQuery('product', productQuery);
    goodsQuery.find().then(function (results) {
        if (results.length<1 && page==1){
            res.json(assert.con2json(200, '没有搜索到商品', results));
        }else if(results.length<1){
            res.json(assert.con2json(200, '没有更多搜索商品了', results));
        }else {
            var response_content = [];
            results.forEach(function (item) {
                var temp = assert.obj2dic(item.get('product'), ['images', 'price', 'country', 'title', 'salePrice']);
                temp.objectId = item.id;
                temp['images'] = temp['images'][0];
                response_content.push(temp);
            });
            res.json(assert.con2json(200, '搜索商品成功', response_content));
        }
    }, function (error) {
        res.json(assert.con2json(400, '搜索商品失败'))
    });
};
// 删除购物车内的商品
function deleteShoppingItem(products, user) {
    var Product = Parse.Object.extend('OPStoreGoods');
    var query = new Parse.Query('KDShoppingItem');
    var waitDel = [];
    for (var i=0; i<products.length; i++){
        var product = new Product();
        product.id = products[i]['product'];
        waitDel.push(product);
    }
    query.equalTo('user', user);
    query.containedIn('product', waitDel);
    query.find().then(function (result) {
        result.map(function (obj) {
            obj.destroy();
        });
    },function (error) {
        console.log(error);
    });
}
// 将登陆用户的浏览记录写到数据控中
